import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MaxPriceByShop {
    public static class MaxPriceMapper extends Mapper<LongWritable, Text, Text, FloatWritable> {
        private Text shopName = new Text();
        private FloatWritable price = new FloatWritable();

        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] fields = value.toString().split(",");
            if (fields[0].equals("update_time")){
                return;
            }
            if (fields.length == 7) {
                shopName.set(fields[6]);
                price.set(Float.parseFloat(fields[3]));
                context.write(shopName, price);
            }
        }
    }

    public static class MaxPriceReducer extends Reducer<Text, FloatWritable, Text, FloatWritable> {
        private FloatWritable maxPrice = new FloatWritable();

        public void reduce(Text key, Iterable<FloatWritable> values, Context context) throws IOException, InterruptedException {
            float max = Float.MIN_VALUE;
            for (FloatWritable value : values) {
                max = Math.max(max, value.get());
            }
            maxPrice.set(max);
            context.write(key, maxPrice);
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "Max Price by Shop");
        job.setJarByClass(MaxPriceByShop.class);
        job.setMapperClass(MaxPriceMapper.class);
        job.setReducerClass(MaxPriceReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FloatWritable.class);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}

